//1引入
import axios from 'axios';
import { getToken, setToken, setRefreshToken } from 'token.js';
import { refreshToken, isRefreshRequest } from './refreshToken.js';

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
//2创建axios实例
let service = axios.create({
  baseURL: 'http://localhost:8088',
  timeout: 6000,
  headers: {
    Authorization: `Bearer ${getToken()}`,
  },
});
// 返回其他状态吗
service.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500; // 默认的
};

// 跨域请求，允许保存cookie
service.defaults.withCredentials = true;

//创建拦截器
service.interceptors.request.use(
  (config) => {
    // 是否需要设置 token
    const isToken = (config.headers || {}).isToken === false;
    const token = store.getters.access_token;
    if (token && !isToken) {
      config.headers['Authorization'] = token; // 让每个请求携带自定义token
    }
    return config;
  },
  (error) => {
    console.log(error);
    return Promise.reject(error);
  },
);

service.interceptors.response.use(
  async (res) => {
    if (res.headers.Authorization) {
      const token = res.headers.Authorization.replace('Bearer ', '');
      setToken(token);
      service.defaults.headers.Authorization = `Bearer ${token}`;
    }
    if (res.headers.refreshtoken) {
      const refreshtoken = res.headers.refreshtoken.replace('Bearer', '');
      setRefreshToken(refreshtoken);
    }
    if (res.data.code === 401 && isRefreshRequest(res.config)) {
      // 刷新token
      const isSuccess = await refreshToken();
      if (isSuccess) {
        // 重新请求
        res.config.headers.Authorization = `Bearer ${getToken()}`;
        const resp = service.request(res.config);
        return resp;
      } else {
        console.log('登录页');
      }
    }
    return res.data;
  },
  (error) => {
    return Promise.reject(error);
  },
);

export default service;
